import React,{useState,useEffect} from 'react'
import axios from 'axios'
import { Table, Tag, Space, Button ,Modal,Popover,Switch} from 'antd'
import { DeleteOutlined, EditOutlined,ExclamationCircleOutlined} from '@ant-design/icons';

const { confirm } = Modal;

function RightList() {
  const [dataSource, setdataSource] = useState([])
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => <b> {id}</b>,
    },
    {
      title: '权限名称',
      dataIndex: 'title',
    },
    {
      title: '权限路径',
      dataIndex: 'key',
      render: (path) => <Tag color="gold">{path}</Tag>,
    },
    {
      title: '操作',
      render: (item) => <Space>
        <Button danger shape="circle" ghost icon={<DeleteOutlined />} onClick={() => handleDelete(item)}></Button>
        <Popover content={<div style={{ textAlign: 'center' }}><Switch  checked={item.pagepermisson} onChange={ ()=>handleEdit(item)}/></div>} title="配置项" trigger={item.pagepermisson===undefined?'':'click'}>
          <Button type="primary" shape="circle" ghost icon={<EditOutlined />} disabled={item.pagepermisson===undefined}></Button>
        </Popover>
      </Space>,
    },
  ]
  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = () => {
    axios.get('/rights?_embed=children').then(response => {
      const list = response.data
      list.forEach(item => {
        if (!item.children?.length) {
          item.children=''
        }
      })
      setdataSource(list)
    })
  }
  const handleDelete = (item) => {
    confirm({
      title: '您确定要删除此项数据吗?',
      icon: <ExclamationCircleOutlined />,
      okText:"确认",
      cancelText: "取消",
      
      onOk() {
        confirmDelete(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  /**
   * @description 编辑
   */
  const handleEdit = (item) => {
    item.pagepermisson=item.pagepermisson===1?0:1
    setdataSource([...dataSource])

    if (item.grade === 1) {
      axios.patch(`/rights/${item.id}`, {
        pagepermisson:item.pagepermisson
      })
    }
    // 二级菜单
    else {
      axios.patch(`/children/${item.id}`, {
        pagepermisson:item.pagepermisson
      })
    }
    
  }
  //删除
  const confirmDelete = (item) => { 
    // 当前页面同步状态+后端同步
    // 一级菜单
    if (item.grade === 1) {
      setdataSource(dataSource.filter(data => data.id !== item.id))
      axios.delete(`/rights/${item.id}`)
    }
    // 二级菜单
    else {
      let list = dataSource.filter(data => data.id === item.rightId)
      list[0].children=[...list[0].children.filter(data=>data.id!==item.id)]
    }
  }

  return (
    <div>
      <Table dataSource={dataSource} columns={columns}
        pagination={{
        pageSize: 5,
      }}/>
    </div>
  )
}

export default RightList